package util

import (
	commUtil "gin/common/util"
	genConf "gin/generator/config"
	genCon "gin/generator/constant"
	genEntity "gin/generator/entity"
	"log"
	"regexp"
	"strconv"
	"strings"
	"time"
)

/****
初始化表信息
*****/
func InitTable(genTable genEntity.GenTable, operName string) genEntity.GenTable {
	now := time.Now()

	genTable.TbName = genTable.TbName
	genTable.ClassName = convertClassName(genTable.TbName)
	genTable.PackageName = genConf.PackageName()
	genTable.ModuleName = getModuleName(genConf.PackageName())
	genTable.BusinessName = getBusinessName(genTable.TbName)
	genTable.FunctionName = replaceText(genTable.TbName)
	genTable.FunctionAuthor = (genConf.Author())
	genTable.CreateBy = genConf.Author()
	genTable.CreateTime = now
	genTable.UpdateTime = now
	return genTable
}

//
func convertClassName(tableName string) string {
	autoRemovePre := genConf.AutoRemovePre()
	tablePrefix := genConf.TablePrefix()
	if autoRemovePre && tablePrefix != "" {
		searchList := strings.Split(tablePrefix, ",")
		tableName := replaceFirst(tableName, searchList)
		log.Panic(tableName)
	}
	return commUtil.ConvertToCamelCase(tableName)
}

//批量替换前缀
func replaceFirst(replacementm string, searchList []string) string {
	var text = replacementm
	for _, searchString := range searchList {
		if startsWith(searchString, genConf.TablePrefix()) {
			// 使用strings.Replace函数进行替换，将searchString替换为空字符串
			text = strings.Replace(text, searchString, "", 1)
		}
		break
	}
	return text
}

// startsWith函数用于检查字符串s是否以指定的前缀prefix开始
func startsWith(string, prefix string) bool {
	return len(string) >= len(prefix) && string[:len(prefix)] == prefix
}

//获取模块名称
func getModuleName(packageName string) string {
	lastIndex := strings.LastIndex(packageName, ".")
	nameLength := len(packageName)
	if lastIndex == -1 {
		return packageName
	}
	return packageName[lastIndex+1 : nameLength]
}

// getBusinessName从给定的表名中截取最后一个下划线之后的部分作为业务名
func getBusinessName(tableName string) string {
	lastIndex := strings.LastIndex(tableName, "_")
	nameLength := len(tableName)
	if lastIndex == -1 {
		return tableName
	}
	return tableName[lastIndex+1 : nameLength]
}

// replaceText对输入的文本进行关键字替换，将"表"和"若依"替换为空字符串
func replaceText(text string) string {
	// 定义匹配"表"或"若依"的正则表达式模式
	pattern := regexp.MustCompile("(?:表|若依)")
	// 使用正则表达式进行替换操作
	return pattern.ReplaceAllString(text, "")
}

//初始化列属性字段
func InitColumnField(column genEntity.GenTableColumn, table genEntity.GenTable) genEntity.GenTableColumn {
	dataType := getDbType(column.ColumnType)
	columnName := column.ColumnName

	//column.TableId = table.TableId
	column.CreateBy = table.CreateBy
	column.JavaField = commUtil.ConvertToCamelCase(columnName)
	column.ColumnType = genCon.TYPE_STRING
	if arraysContains(genCon.COLUMNTYPE_STR, dataType) || arraysContains(genCon.COLUMNTYPE_TEXT, dataType) {
		// 字符串长度超过500设置为文本域
		columnLength := getColumnLength(column.ColumnType)
		var htmlType string
		if columnLength >= 500 || arraysContains(genCon.COLUMNTYPE_TEXT, dataType) {
			htmlType = genCon.HTML_TEXTAREA
		} else {
			htmlType = genCon.HTML_INPUT
		}
		column.HtmlType = htmlType
	} else if arraysContains(genCon.COLUMNTYPE_TIME, dataType) {
		column.JavaType = genCon.TYPE_DATE
		column.HtmlType = genCon.HTML_DATETIME
	} else if arraysContains(genCon.COLUMNTYPE_NUMBER, dataType) {
		column.HtmlType = genCon.HTML_INPUT
		//如果是浮点型 统一用BigDecimal
		str := strings.Split(strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(column.ColumnType, "("), ")")), ",")
		// 如果是浮点型 统一用BigDecimal
		if len(str) == 2 && str[1] != "" && str[0] != "" {
			num, err := strconv.Atoi(str[1])
			if err == nil && num > 0 {
				column.JavaType = genCon.TYPE_BIGDECIMAL
				//return
			}
		}

		// 如果是整形
		if len(str) == 1 && str[0] != "" {
			num, err := strconv.Atoi(str[0])
			if err == nil && num <= 10 {
				column.JavaType = genCon.TYPE_INTEGER
				//return
			}
		}

		// 长整形
		column.JavaType = genCon.TYPE_LONG
	}
	//TODO   插入字段（默认所有字段都需要插入）
	column.IsInsert = genCon.REQUIRE

	var isPk bool = false
	pk := column.IsPk
	if pk == "1" {
		isPk = true
	}
	// 编辑字段
	if !arraysContains(genCon.COLUMNNAME_NOT_EDIT, columnName) && !isPk {
		column.IsEdit = genCon.REQUIRE
	}

	// 列表字段
	if !arraysContains(genCon.COLUMNNAME_NOT_LIST, columnName) && isPk {
		column.IsList = genCon.REQUIRE
	}
	// 查询字段
	if !arraysContains(genCon.COLUMNNAME_NOT_QUERY, columnName) && !isPk {
		column.IsList = genCon.REQUIRE
	}

	// 查询字段类型
	if strings.HasSuffix(strings.ToLower(columnName), "name") {
		column.QueryType = genCon.QUERY_LIKE
	}

	//状态字段设置单选框
	if strings.HasSuffix(strings.ToLower(columnName), "status") {
		column.HtmlType = genCon.HTML_RADIO
	} else if strings.HasSuffix(strings.ToLower(columnName), "type") || (strings.HasSuffix(strings.ToLower(columnName), "sex")) {
		// 类型&性别字段设置下拉框
		column.HtmlType = genCon.HTML_SELECT
	} else if strings.HasSuffix(strings.ToLower(columnName), "image") {
		// 图片字段设置图片上传控件
		column.HtmlType = genCon.HTML_IMAGE_UPLOAD
	} else if strings.HasSuffix(strings.ToLower(columnName), "file") {
		// 文件字段设置文件上传控件
		column.HtmlType = genCon.HTML_FILE_UPLOAD
	} else if strings.HasSuffix(strings.ToLower(columnName), "content") {
		// 内容字段设置富文本控件
		column.HtmlType = genCon.HTML_EDITOR
	}
	now := time.Now()
	column.CreateTime = now
	column.UpdateTime = now
	return column
}

//获取数据库类型字段
func getDbType(columnType string) string {
	if strings.Index(columnType, "(") > 0 {
		return strings.SplitN(columnType, "(", 2)[0]
	}
	return columnType
}

//校验数组案发=是否包含指定值
func arraysContains(arr []string, targetValue string) bool {
	for _, value := range arr {
		if value == targetValue {
			return true
		}
	}
	return false
}

func getColumnLength(columnType string) int {
	if strings.Index(columnType, "(") > 0 {
		length := strings.TrimSpace(strings.TrimSuffix(strings.TrimPrefix(columnType, "("), ")"))
		value, err := strconv.Atoi(length)
		if err != nil {
			return 0
		}
		return value
	}
	return 0
}
